package com.bingxue.edu.framework.job;

import com.bingxue.edu.common.enums.CommonStatusEnum;
import com.bingxue.edu.management.system.model.entity.ScheduleJob;
import com.bingxue.edu.management.system.service.ScheduleJobService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.bingxue.edu.management.system.model.entity.table.ScheduleJobTableDef.SCHEDULE_JOB;

/**
 * 定时任务初始化
 * 在定时任务启用时，初始化数据库里面状态为启用的定时任务
 *
 * @author panbo
 * @since 2024/8/2
 */
@Slf4j
@Component
@ConditionalOnProperty(prefix = "spring.quartz", name = "job-store-type", havingValue = "MEMORY", matchIfMissing = true)
@RequiredArgsConstructor
public class SchedulerJobInitializer implements ApplicationRunner {

    private final ScheduleJobService scheduleJobService;

    private final QuartzSchedulerService quartzSchedulerService;

    @Override
    public void run(ApplicationArguments args) {
        List<ScheduleJob> jobList = scheduleJobService.queryChain().where(SCHEDULE_JOB.STATUS.eq(CommonStatusEnum.ENABLED)).list();
        jobList.forEach(scheduleJob -> {
            try {
                quartzSchedulerService.addJob(scheduleJob);
            } catch (Exception e) {
                log.error("初始化加载定时任务[{}]失败！", scheduleJob.getJobKey(), e);
            }
        });
    }
}
